#!-*- encoding:utf8 -*-
from django import forms
from osmp.host.models import Product
from django.contrib.auth.models import User
from django.db.models import Q
from osmp.users.models import UserProfile
from osmp import settings
import time

TITLE_CHOICES = [
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
]

class FlowForm(forms.Form):
    pids = Product.objects.all()
    pids_choices = []
    for e in pids:
        pids_choices.append((e.id, e.name))
    
    auths = UserProfile.objects.filter(role = '研发经理')
    auth_choices = []
    for e in auths:
        auth_choices.append((str(e.user), str(e.user)))
 
    ops = UserProfile.objects.filter(Q(role = '运维工程师')|Q(secondrole__contains = '运维工程师'))
    ops_choices = []
    for e in ops:
        ops_choices.append((str(e.user), str(e.user)))

    tname = forms.CharField(max_length=255, label='操作单名称')
    pid = forms.CharField(max_length=255,  widget=forms.Select(choices=pids_choices), label='产品线名称')
    auth_uid = forms.CharField(max_length=20,  widget=forms.Select(choices=auth_choices), label='审核人')
    op_uid = forms.CharField(max_length=20,   widget=forms.Select(choices=ops_choices), label='操作人员')
    hid = forms.CharField(widget=forms.Textarea(), label="主机列表")
    detail = forms.CharField(widget=forms.Textarea(), label="操作单描述")
    attach = forms.FileField(label='附件', required=False)
#attach = forms.CharField( widget=forms.widgets.FileInput(attrs={'size':42}), label='附件', required=False)


    def clean_detail(self):
        detail = self.cleaned_data['detail']
        if not detail:
            raise forms.ValidationError("Not enough words!")
        return detail
    
    def clean_auth_uid(self):
        id = self.cleaned_data['auth_uid']
        user = User.objects.get(username = id)
        if not user:
            raise forms.ValidationError("User  Not Exist!")
        return user.username
 
    def clean_op_uid(self):
        id = self.cleaned_data['op_uid']
        user = User.objects.get(username = id)
        if not user:
            raise forms.ValidationError("User  Not Exist!")
        return user.username

    def clean_pid(self):
        data = self.cleaned_data['pid']
        id = ''
        name = ''
        try:
            id = int(data)
        except:
            name = data
        if not data:
            raise forms.ValidationError("DATA  Not Exist!")

        pid = ''
        if id:
            obj = Product.objects.get(id = id)
            if obj:
                pid = obj.id
        else:
            objs = Product.objects.filter(name = name)
            if objs:
                pid = objs[0].id    
        
        if not pid:
            raise forms.ValidationError("DATA  Not Exist!")
        return pid


    def clean_attach(self):
        attach = self.files.get('attach', None)
        if attach:
            localname = "%s.%d" % (attach.name, time.time())
            path = "%s/%s" % (settings.UPLOAD_PATH, localname)
            fd = open(path, "w")
            fd.write(attach.read())
            fd.close()
            return localname
        else:
            return ""

 
   
